package com.api.devices.controller;

import com.alibaba.fastjson2.JSONObject;
import com.api.common.core.controller.BaseController;
import com.api.common.core.domain.AjaxResult;
import com.api.common.core.page.TableDataInfo;
import com.api.common.utils.MessageUtils;
import com.api.devices.domain.query.IpcQuery;
import com.api.devices.domain.query.ResourceQuery;
import com.api.devices.domain.vo.IpcVo;
import com.api.devices.service.IResourceService;
import com.api.devices.service.IiPcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/resource")
public class ResourceController extends BaseController {
    private static int pageSize = 99999999;

//    @Autowired
//    IClusterRealtimeService clusterRealtimeService;

    @Autowired
    IResourceService resourceService;

    @Autowired
    IiPcService ipcService;


    @PostMapping("/latestNews")
    public AjaxResult getLatestNews(@RequestBody IpcVo vo) {
        IpcQuery ipcQuery = ipcService.search(vo);
        return AjaxResult.success(resourceService.latestNews(ipcQuery.getResourceTableName()));
    }

    @PostMapping("/latest")
    public AjaxResult getLastest(@RequestHeader("App-Language") String appLang
            , @RequestBody JSONObject jo) {
//        ipcCodeList: ['001', '002']
        if (jo.containsKey("ipcCodeList")) {
            Map<String, JSONObject> map = new HashMap<>();
            List<String> list = jo.getList("ipcCodeList", String.class);
            for (String ipcCode : list) {
                try {
                    map.put(ipcCode, JSONObject.from(resourceService.latest(ipcCode)));
                } catch (Exception e) {
                    JSONObject paramJO = new JSONObject();
                    paramJO.put("error", true);
                    paramJO.put("msg", MessageUtils.message("common.run.error") + ":" + e.getMessage());
                    map.put(ipcCode, paramJO);
                }
            }
            return AjaxResult.success(map);
        } else {
            return AjaxResult.warn(MessageUtils.message("common.must.input"));
        }
    }

    @PostMapping("/list")
    public TableDataInfo list(@RequestBody IpcVo vo) {
        try {
            if (ObjectUtils.isEmpty(vo.getStartTime())
                    || ObjectUtils.isEmpty(vo.getStartTime())) {
                return getDataPageError("开始时间或结束时间为空");
            }
//            IpcQuery ipcQuery = ipcService.search(vo);
//            String resourceTableName = ipcQuery.getResourceTableName();

            return getDataTable(resourceService.resourceList(vo));
        } catch (Exception e) {
            return getDataPageError(e.getMessage());
        }
    }
}
